<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\tool\Result;
use app\common\model\Role;
use addons\Builder\facade\Builder;
use think\exception\ValidateException;
use think\facade\View;
use think\Response;
use think\response\Json;

class Admin extends Base
{
    protected string $pk = 'id';

    protected string $model = '\app\common\model\Admin';

    protected string $validate = 'Admin';

    protected array $hasOne = ['role'];

    public function index(): string
    {
        return Builder::Table()
            ->autoStructure($this->model, $this->pk, 'adminBarDemo,140', false, false)
            ->addTopButtons(['add' => ['size' => '50%']])
            ->addRightButtons(['edit' => ['size' => '50%'], 'delete'])
            ->addSearch([
                ['admin_name__mobile__comment', '用户名/手机/备注', 'input,Like'],
                ['role_id', '角色类型', 'select', self::getRole()]
            ])
            ->addExtraHtml(['admin'])
            ->fetch();
    }

    public static function getRole(): array
    {
        return Role::column('title', 'id');
    }

    public function save($param = [], $model = true): Json
    {
        return parent::save($param, $model); // TODO: Change the autogenerated stub
    }

    public function password(): Response|string
    {
        if ($this->request->isPost()) {
            try {
                $param = $this->request->post();
                $this->validate($param, 'AdminPassword');
                if (md5($param['old']) != $this->admin->password) return Result::fail('原密码错误');
                $this->model::update(['password' => md5($param['password'])], ['id' => $this->admin->id]);
                \app\common\model\Logs::adds('管理员【' . $this->admin->admin_name . '】修改了密码');
                session('admin_id', null);
                return Result::success('已修改');
            } catch (ValidateException $e) {
                return Result::fail($e->getError());
            }
        }
        return View::fetch();
    }

}
